package com.joolun.cloud.common.jiguang.util;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.joolun.cloud.common.jiguang.config.JiguangConfigProperties;
import com.joolun.cloud.common.jiguang.entity.InitParm;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import java.util.Date;

/**
 * 极光工具
 * http://docs.jiguang.cn/jmessage/guideline/jmessage_guide/
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class JiguangUtils {

	private final JiguangConfigProperties jiguangConfigProperties;

	/**
	 * 获取初始化参数
	 * @return
	 */
	public InitParm getConfig(){
		InitParm initParm = new InitParm();
		String appkey = jiguangConfigProperties.getAppKey();
		String random_str = RandomUtil.randomNumbers(36);
		long timestamp = new Date().getTime();
		String signatureStr = "appkey=%s&timestamp=%s&random_str=%s&key=%s";
		String signature = String.format(signatureStr
				, appkey, timestamp, random_str,jiguangConfigProperties.getSecret());
		signature = SecureUtil.md5(signature);
		initParm.setAppkey(appkey);
		initParm.setFlag(jiguangConfigProperties.getFlag());
		initParm.setRandom_str(random_str);
		initParm.setSignature(signature);
		initParm.setTimestamp(timestamp);
		return initParm;
	}

	/**
	 * 获取HTTP 验证
	 * @return
	 */
	public String getAuthString(){
		String str = jiguangConfigProperties.getAppKey() + ":" + jiguangConfigProperties.getSecret();
		return Base64Encoder.encode(str);
	}

	/**
	 * 获取消息
	 * @param userName
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public String getMessages(String userName, String beginTime, String endTime){
		String authorization = "Basic " + this.getAuthString();
		userName = StrUtil.isNotBlank(userName) ? "/"+userName : "";
		String url = "https://report.im.jpush.cn/v2/users" + userName +"/messages?count=1000&begin_time=" + beginTime + "&end_time=" + endTime;
		return HttpRequest
				.get(url)
				.header("Authorization",authorization)
				.execute().body();
	}
}
